<script setup lang="ts">
import { computed, onMounted, reactive, Ref, ref, watch } from "vue";
import { storeToRefs } from "pinia";
import { ElMessage, ElMessageBox } from "element-plus";
import useUserListStore from "@/pinia/modules/permissions/userStore/userStore.ts";
import { role, userItem } from "@/api/permissions/userApi/interface.ts";
import { addOrUpdateUserAPI, batchRemoveAPI, doAssignRoleAPI, fetchRoleListAPI } from "@/api/permissions/userApi/userApi.ts";

const useListStore = useUserListStore();

const { pageParams, userList, total } = storeToRefs(useListStore);

const userFormRef = ref(null);
/* 是否显示添加用户或者编辑用户的弹框 */
const userDrawer: Ref<boolean> = ref<boolean>(false);
/* 是否是编辑用户状态 */
const editUser: Ref<boolean> = ref(false);
/* 添加或者修改用户的表单数据对象 */
const userFormData = reactive<userItem>({
  name: "",
  username: "",
  password: "",
});
/* 搜索用户关键字 */
const username = ref<string>("");
/* 添加或者修改用户的表单规则对象 */
const userFormRules = {
  name: [
    { required: true, message: "请输入用户昵称", trigger: "blur" },
  ],
  username: [
    { required: true, message: "请输入用户姓名", trigger: "blur" },

  ],
  password: [
    { required: true, message: "请输入用户密码", trigger: "blur" },
  ],
};

/* 是否显示添加分配角色的弹框 */
const roleDrawer: Ref<boolean> = ref<boolean>(false);
/* 是否全选 */
const checkedAll: Ref<boolean> = ref<boolean>(false);
/* 所有角色列表 */
const allRolesList: Ref<role[]> = ref<role[]>([]);
/* 拥有的角色列表 */
const assignRoles: Ref<role[]> = ref<role[]>([]);
/* 待删除的用户列表 */
const selectionList = ref<userItem[]>([]);
/* 获取用户列表的回调函数 */
const fetchUserList = async () => {
  try {
    await useListStore.fetchUserList();
  } catch (error: any) {
    ElMessage.error(error.message);
  }
};


/* 点击删除用户按钮的回调函数 */
const handleDeleteUser = async (user: userItem) => {
  const confirm: string = await ElMessageBox.confirm(`确定删除${user.name}吗`, "警告", { type: "warning" }).catch((error: any) => error);
  if (confirm === "cancel") return;
  try {
    const deleteResult: string = await useListStore.deleteUser(user.id as number);
    await fetchUserList();
    ElMessage.success(deleteResult);
  } catch (error: any) {
    ElMessage.error(error.message);
  }
};

/* 分页器size发生变化的回调函数 */
const handleSizeChange = () => {
  fetchUserList();

};
/* 分页器page发生变化的回调函数 */
const handleCurrentChange = () => {
  fetchUserList();
};

/* 点击添加用户按钮的回调函数 */
const handleAddUser = () => {
  userDrawer.value = true;
  editUser.value = false;
};

/* 点击编辑用户按钮的回调函数 */
const handleEditUser = (user: userItem) => {
  Object.assign(userFormData, user);
  userDrawer.value = true;
  editUser.value = true;
};

/* 点击添加或编辑用户确定按钮的回调函数 */
const handleSubmit = async () => {
  const valida: boolean = await userFormRef.value.validate(() => {
  }).catch((error: any) => error);
  if (!valida) return;
  try {
    await addOrUpdateUserAPI(userFormData);
    await fetchUserList();
    userDrawer.value = false;
    ElMessage.success(editUser.value ? "编辑用户成功" : "添加用户成功");
  } catch (error: any) {
    ElMessage.error(error.message);
  }
};


/* 点击搜索按钮的回调函数 */
const handleSearch = () => {
  if (pageParams.username === "") return ElMessage.warning("输入为空");
  fetchUserList();
  /*userListInfo.value.records = userListInfo.value.records.filter(item => item.username === username.value);*/
};

/* 点击重置按钮的回调函数 */
const handleReset = () => {
  useListStore.pageParams.page = 1;
  useListStore.pageParams.limit = 10;
  useListStore.pageParams.username=undefined
  username.value = "";
  fetchUserList();
};

const handleClose = () => {
  userFormRef.value.resetFields();
  Object.assign(userFormData, {
    name: "",
    username: "",
    password: "",
  });
};

/* 用户分配角色按钮的回调函数 */
const handleAssignRoles = async (user: userItem) => {
  Object.assign(userFormData, user);
  const { data: { allRolesList: allRoles, assignRoles: roles } } = await fetchRoleListAPI(user.id as number);
  allRolesList.value = allRoles;
  assignRoles.value = roles;
  roleDrawer.value = true;
};

/* 全选框的change事件 */
const changeAll = (value: boolean) => {
  if (value) {
    assignRoles.value = allRolesList.value;
  } else {
    assignRoles.value = [];
  }
};
/* 复选框组的change事件 */
const changeChecked = (value: role[]) => {
  if (value.length === allRolesList.value.length) {
    checkedAll.value = true;
  } else {
    checkedAll.value = false;
  }
};

/* 分配角色按钮确定的回调函数 */
const assignRolesSubmit = async () => {
  try {
    const params: { userId: number, roleIdList: number[] } = {
      userId: userFormData.id,
      roleIdList: assignRoles.value.map(item => item.id),
    };
    await doAssignRoleAPI(params);
    await fetchUserList();
    roleDrawer.value = false;
    ElMessage.success("用户分配角色成功");
  } catch (error: any) {
    ElMessage.error(error.message);
  }
};

/* 点击批量删除用户的按钮 */
const handleBatchRemove = async () => {
  try {
    await batchRemoveAPI(selectionList.value.map(item => item.id));
    await fetchUserList();
    ElMessage.success("批量删除用户成功");
  } catch (error: any) {
    ElMessage.error(error.message);

  }
};

/*  表格的勾选事件*/
const handleSelectionChange = (selection: userItem[]) => {
  selectionList.value = selection;
};
const userDrawerTitle = computed(() => editUser.value ? "编辑用户" : "添加用户");

onMounted(() => {
  fetchUserList();
});

watch(() => roleDrawer.value, (newValue: boolean) => {
  if (newValue) {
    checkedAll.value = allRolesList.value.length === assignRoles.value.length;
  }
});
</script>

<template>
  <div class="user">
    <el-card>
      <el-form inline class="form">
        <el-form-item label="用户名">
          <el-input placeholder="请输入搜索用户名" v-model="pageParams.username"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
          <el-button type="warning" icon="InfoFilled" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <el-button type="primary" icon="Plus" @click="handleAddUser">添加用户</el-button>
      <el-button type="info" icon="Delete" @click="handleBatchRemove">批量删除用户</el-button>
      <el-table border stripe :data="userList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="80px" align="center"></el-table-column>
        <el-table-column label="序号" type="index" width="80px" align="center"></el-table-column>
        <el-table-column label="用户ID" prop="id" width="80px" align="center"></el-table-column>
        <el-table-column label="用户名字" prop="username" width="200px" align="center"></el-table-column>
        <el-table-column label="用户名称" prop="name" width="200px" align="center"></el-table-column>
        <el-table-column label="拥有角色" prop="roleName" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column label="创建时间" prop="createTime" align="center"></el-table-column>
        <el-table-column label="更新时间" prop="updateTime" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{row}">
            <el-button type="primary" icon="User" @click="handleAssignRoles(row)">分配角色</el-button>
            <el-button type="warning" icon="Edit" @click="handleEditUser(row)">编辑用户</el-button>
            <el-button type="danger" icon="Delete" @click="handleDeleteUser(row)">删除用户</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="pageParams.page"
        v-model:page-size="pageParams.limit"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="Number(total||0)"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange">
      </el-pagination>
    </el-card>
    <el-drawer v-model="userDrawer" :title="userDrawerTitle" @close="handleClose">
      <el-form label-width="80px" :model="userFormData" :rules="userFormRules" ref="userFormRef">
        <el-form-item label="用户姓名" prop="username">
          <el-input placeholder="请输入用户姓名" v-model="userFormData.username"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="name">
          <el-input placeholder="请输入用户昵称" v-model="userFormData.name"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input placeholder="请输入用户密码" v-model="userFormData.password"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="danger">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-drawer>

    <el-drawer v-model="roleDrawer" title="用户分配角色" @close="handleClose">
      <el-form label-width="80px" ref="userFormRef">
        <el-form-item label="用户姓名">
          <el-input disabled v-model="userFormData.username"></el-input>
        </el-form-item>
        <el-form-item label="角色列表">
          <el-checkbox v-model="checkedAll" @change="changeAll">全选</el-checkbox>——
          <el-checkbox-group v-model="assignRoles" @change="changeChecked">
            <el-checkbox v-for="(item) in allRolesList" :label="item" :key="item.id">{{ item.roleName }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="danger">取消</el-button>
        <el-button type="primary" @click="assignRolesSubmit">确定</el-button>
      </template>
    </el-drawer>


  </div>
</template>

<style scoped lang="scss">
.user {

  .el-card {
    margin-bottom: 10px;

    .form {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .el-table {
      margin: 10px 0;
    }

    .el-pagination {
      display: flex;
      justify-content: center;
    }
  }
}
</style>
